package main

import (
	"awesomeProject2/src/test2020/stats/config"
	"awesomeProject2/src/test2020/stats/constant"
	"awesomeProject2/src/test2020/stats/request"
	"fmt"
	"math/rand"
	"sync"
	"time"
)

type Context struct {
	lock sync.RWMutex

	// request header, data is in the header.ini
	headers map[string]string

	requestContext request.Context

	// context init state
	init bool
}

func (c *Context) Init() {
	beginTime := time.Now().UnixNano() / int64(time.Millisecond)
	fmt.Println("init execute")
	// the context has been init
	if c.init {
		fmt.Println("\treturn")
		return
	}
	c.lock.Lock()
	defer func() {
		c.lock.Unlock()
	}()
	// config
	constant.InitConfig()
	// header
	c.headers = config.ToMap(constant.HeaderPath)
	constant.SetHeaders(c.headers)

	// request
	c.requestContext = request.Context{}
	c.requestContext.Init()
	// 设置请求
	c.requestContext.SetUrl(constant.BaseUrl, constant.IndexUrl, "")
	c.requestContext.RefreshLevel()
	// set init
	c.init = true
	// rand sleep time
	rand.Seed(time.Now().UnixNano())
	var sleep = rand.Intn(1000)
	time.Sleep(time.Duration(sleep) * time.Millisecond)
	// calculation execution time
	endTime := (time.Now().UnixNano() / int64(time.Millisecond)) - beginTime
	fmt.Printf("completed"+"(time:%d(%d)ms)", endTime, sleep)
	// empty line
	fmt.Println()
}

func (c *Context) Destroy() {
	fmt.Println("destroy execute")
	// the context is not init
	if !c.init {
		fmt.Println("return")
		return
	}
	c.lock.Lock()
	defer c.lock.Unlock()
	// request
	c.requestContext.Destroy()
	// config destroy
	constant.DestroyConfig()
	// context header set to nil
	c.headers = nil
	// init set to false
	c.init = false
	fmt.Println("completed")
}
